package springfox.documentation.swagger;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import springfox.documentation.BeanUtils;
import springfox.documentation.spi.schema.EnumTypeDeterminer;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.readers.parameter.ApiParamParameterBuilder;
import springfox.documentation.swagger.readers.parameter.ApiParamParameterBuilderNew;
import springfox.documentation.swagger.readers.parameter.SwaggerExpandedParameterBuilder;
import springfox.documentation.swagger.readers.parameter.SwaggerExpandedParameterBuilderNew;
import springfox.documentation.swagger.schema.ApiModelPropertyPropertyBuilder;
import springfox.documentation.swagger.schema.ApiModelPropertyPropertyBuilderNew;


@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration
public class ReplaceSwaggerBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 替换bean
        if (bean instanceof ApiModelPropertyPropertyBuilder) {
            return new ApiModelPropertyPropertyBuilderNew((DescriptionResolver) BeanUtils.getFieldValue(bean, "descriptions"));
        }


        if (bean instanceof ApiParamParameterBuilder) {
            return new ApiParamParameterBuilderNew((DescriptionResolver) BeanUtils.getFieldValue(bean, "descriptions"),
                    (EnumTypeDeterminer) BeanUtils.getFieldValue(bean, "enumTypeDeterminer"));
        }


//        if (bean instanceof ModelAttributeParameterExpander) {
//            return new ModelAttributeParameterExpanderNew((FieldProvider) ModelAttributeParameterExpanderNew.getFieldValue(bean, "fields"),
//                    (AccessorsProvider) BeanUtils.getFieldValue(bean, "accessors"),
//                    (EnumTypeDeterminer) BeanUtils.getFieldValue(bean, "enumTypeDeterminer"),
//                    (DocumentationPluginsManager) BeanUtils.getFieldValue(bean, "pluginsManager"));
//        }


        if (bean instanceof SwaggerExpandedParameterBuilder) {
            return new SwaggerExpandedParameterBuilderNew((DescriptionResolver) BeanUtils.getFieldValue(bean, "descriptions"),
                    (EnumTypeDeterminer) BeanUtils.getFieldValue(bean, "enumTypeDeterminer"));
        }

        return bean;
    }
}
